package ru.reaperoq.taskmanager.controllers

import jakarta.servlet.http.HttpServletRequest
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import ru.reaperoq.taskmanager.dto.Response
import ru.reaperoq.taskmanager.exceptions.TaskManagerException
import ru.reaperoq.taskmanager.getUser
import ru.reaperoq.taskmanager.models.File
import ru.reaperoq.taskmanager.repositories.FileRepository
import ru.reaperoq.taskmanager.repositories.UserRepository
import ru.reaperoq.taskmanager.services.JwtService

@RestController
@RequestMapping("/api/files")
class FileController(
    private val fileRepository: FileRepository,
    private val userRepository: UserRepository,
    private val jwtService: JwtService
) {

    @PostMapping("/upload")
    fun uploadFile(@RequestParam("file") file: MultipartFile, req: HttpServletRequest): Response<*> {
        val user = req.getUser(userRepository = userRepository, jwtService = jwtService)
        val saved = fileRepository.save(
                File(
                    data = file.bytes,
                    mimeType = file.contentType ?: "image/jpeg"
                )
            )
        user.files.add(saved)
        userRepository.save(user)
        return Response.success(
            saved
        )
    }

    @DeleteMapping("/{id}/delete")
    fun deleteFile(@PathVariable("id") id: Long, req: HttpServletRequest): Response<*> {
        val file = checkFileBelongsUser(req, id)
        fileRepository.delete(file)
        return Response.success(
            file.id
        )

    }

    @GetMapping("/{id}")
    fun downloadFile(@PathVariable("id") id: Long, req: HttpServletRequest): ResponseEntity<*> {
        val file = checkFileBelongsUser(req, id)
        return ResponseEntity
            .status(HttpStatus.OK)
            .headers(HttpHeaders().apply {
                contentType = MediaType.parseMediaType(file.mimeType)
            })
            .body(file.data)
    }

    private fun checkFileBelongsUser(req: HttpServletRequest, fileId: Long): File {
        val user = req.getUser(userRepository = userRepository, jwtService = jwtService)
        val file = fileRepository.findFileById(fileId) ?: throw TaskManagerException.NotFound("Файл не найден")
        if (!file.users.map { it.id }.contains(user.id)) {
            throw TaskManagerException.NotFound("Файл не найден")
        }
        return file
    }
}